package com.itheima.project.handler.impl;

import com.itheima.project.feign.CustomerAdapterFeign;
import com.itheima.project.feign.UserAdapterFeign;
import com.itheima.project.handler.CacheTokenHandler;
import com.itheima.project.handler.LoginAuthHandler;
import com.itheima.project.constant.security.OauthConstant;
import com.itheima.project.core.enums.security.AuthEnum;
import com.itheima.project.exception.ProjectException;
import com.itheima.project.vo.security.EnterpriseVo;
import com.itheima.project.vo.security.UserVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.endpoint.TokenEndpoint;
import org.springframework.stereotype.Component;
import org.springframework.web.HttpRequestMethodNotSupportedException;

import java.security.Principal;
import java.util.Map;

/**
 * @ClassName UserpasswordLoginAdapter.java
 * @Description 密码登录处理器实现
 */
@Slf4j
@Component("usernameLoginAuthHandler")
public class UsernameLoginAuthHandlerImpl implements LoginAuthHandler {

    @Autowired
    TokenEndpoint tokenEndpoint;

    @Autowired
    CacheTokenHandler cacheTokenHandler;

    //调用RPC原创服务
    @Autowired
    UserAdapterFeign userAdapterFeign;

    //调用RPC原创服务
    @Autowired
    CustomerAdapterFeign customerAdapterFeign;

    @Override
    public UserVo loginHandler(Principal principal, Map<String, String> parameters,EnterpriseVo enterpriseVo)
                                                  throws HttpRequestMethodNotSupportedException {
        String enterpriseId = String.valueOf(enterpriseVo.getEnterpriseId());
        String username = parameters.get(OauthConstant.USER_NAME_KEY);
        String clientId = parameters.get(OauthConstant.CLIENT_ID_KEY);
        String loginType = parameters.get(OauthConstant.LOGIN_TYPE_KEY);
        username = username+"#"+enterpriseId+"#"+clientId+"#"+loginType;
        parameters.put(OauthConstant.USER_NAME_KEY,username);
        OAuth2AccessToken oAuth2AccessToken = tokenEndpoint.postAccessToken(principal, parameters).getBody();
        return cacheTokenHandler.cacheToken(oAuth2AccessToken);
    }

    @Override
    public UserVo findUserDetail(String loginType, String username, Long enterpriseId) {
        //处理登录
        switch (loginType){
            case OauthConstant.USER_USERNAME:
                return userAdapterFeign.findUserByUsernameAndEnterpriseId(username, enterpriseId).getDatas();
            case OauthConstant.CUSTOMER_USERNAME:
                return customerAdapterFeign.findCustomerByUsernameAndEnterpriseId(username, enterpriseId).getDatas();
            default:
                throw new ProjectException(AuthEnum.LOGIN_FAIL);
        }
    }
}
